﻿using System;
using System.IO;
using System.Xml.Serialization;

namespace CHomeWeather
{
    public abstract class XmlSerializableObject<T> where T : class, new()
    {
        #region Load & Save to configuration file

        /// <summary>
        /// Load configuration from file.
        /// If the configuration file does not exist, a new one with default value will be created and loaded.
        /// </summary>
        /// <returns>A instance of <see cref="Configuration"/> with the value read from config.xml.</returns>
        public static T Load(string fileName)
        {
            if (!Util.IsAbsolutePath(fileName))
            {
                fileName = Path.Combine(Util.ApplicationFolder, fileName);
            }

            T instance = default(T);

            if (File.Exists(fileName))
            {
                using (FileStream stream = new FileStream(fileName, FileMode.Open))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    instance = serializer.Deserialize(stream) as T;
                }
            }
            else
            {
                instance = new T();
            }

            return instance;
        }

        /// <summary>
        /// Save the configuration to file.
        /// </summary>
        /// <param name="configuration">The instance of <see cref="Configuration"/> to be saved.</param>
        public static void Save(string fileName, T instance)
        {
            if (!Util.IsAbsolutePath(fileName))
            {
                fileName = Path.Combine(Util.ApplicationFolder, fileName);
            }

            using (FileStream stream = new FileStream(fileName, FileMode.Create))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                serializer.Serialize(stream, instance);
            }
        }

        #endregion
    }
}
